<?php
/*
 * @Date: 2024-04-21 13:33:53
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-05-13 20:01:58
 * 
 * 长连接websocket事件处理
 */

namespace Ldy;

use Ldy\Lib\DataBackup;


class LdyWebsocket
{

    protected static $onMessageConnection;
    protected static $onMessageData;
    protected static $onMessageRequest;

    public static function onMessage($connection, $data, $request)
    {
        self::$onMessageConnection = $connection;
        self::$onMessageData = $data;
        self::$onMessageRequest = $request;

        self::onMessageGetBackupProgress();
        self::onMessageRestoreDatabases();

    }

    //备份进度
    protected static function onMessageGetBackupProgress(){
        
        if(($type = self::checkType(__FUNCTION__)) === false) return false;

        $backupStatusInfo = DataBackup::instance()->getLockData();

        self::$onMessageConnection->send(self::encodeData($type,$backupStatusInfo));
    }

    //数据库还原进度
    protected static function onMessageRestoreDatabases(){

        if(($type = self::checkType(__FUNCTION__)) === false) return false;

        $restoreStatus = DataBackup::instance()->getRestoreStatus();

        self::$onMessageConnection->send(self::encodeData($type, $restoreStatus));
    }


    protected static function checkType($funName){
        $fun = preg_replace('/([A-Z])/',"_$1", $funName);
        $fun = strtolower($fun);
        $fun = str_replace('on_message_','',$fun);

        return $fun == self::$onMessageData['type'] ? $fun:false;
    }


    public static function encodeData($type, $data = []){
        $res = ["type"=>$type];
        if(!empty($data)) $res['data'] = $data;
        return json_encode($res);
    }
}
